import sys, pickle, os
from pml.Parser.lexer.lexer import Lexer
from pml.Parser.lexer.position import Position
from pml.Parser import ASTBuilder
from pml.Bytecode.BytecodeBuilder import BytecodeBuilder
from pml.Eval.Runner import Bytecode
from pml.Bytecode import constants

argv = sys.argv[1:]

if len(argv) < 2:
    print('Missing parameters')
    sys.exit()

if argv[0] == 'pml':
    lexer = Lexer(Position(argv[1], open(argv[1]), -1, 0, 1))
    tokens = lexer.lexer(None, lexer, None)

    builder = ASTBuilder(iter(tokens), depth=1)
    builder.getNextToken()
    ast = builder.buildAST(None, builder, None)

    builder = BytecodeBuilder(ast)
    bytecodes = builder.buildBytecode(None, builder).obj.value

    with open(os.path.splitext(argv[1])[0] + '.pmc', 'wb') as o:
        pickle.dump(bytecodes, o)

elif argv[0] in ('python', 'py'):
    with open(argv[1] + '.py', encoding='UTF-8') as o:
        program = o.read()
    bytecodes = [
        Bytecode(constants.PYTHON, program, 1, None, None),
        Bytecode(constants.EXIT, None, 2, None, None)
    ]
    with open(argv[1] + '.pmm', 'wb') as o:
        pickle.dump(bytecodes, o)
